<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>优惠卷列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索查询 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input v-model="queryParam.title" placeholder="请输入名称" class="input-with-select" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <template>
            <el-select v-model="queryParam.status" clearable placeholder="请选择状态">
              <el-option v-for="item in queryStatusDict" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSizeChange">搜索</el-button>
          <el-button type="primary" @click="couponFormVisible = true">添加优惠卷</el-button>
        </el-col>
      </el-row>
      <!-- table表格数据 start -->
      <template>
        <el-table :data="couponsDataList" style="width: 100%" max-height="570">
          <!-- 数据表 -->
          <el-table-column fixed prop="title" label="名称" width="150">
          </el-table-column>
          <el-table-column prop="user" label="创建者" width="80">
          </el-table-column>
          <el-table-column prop="money" label="抵扣金额" width="80">
          </el-table-column>
          <el-table-column prop="total_quantity" label="总数量" width="80">
          </el-table-column>
          <el-table-column prop="issued_quantity" label="发放数量" width="80">
          </el-table-column>
          <el-table-column prop="start_time" label="发放开始时间" width="150">
          </el-table-column>
          <el-table-column prop="end_time" label="发放结束时间" width="150">
          </el-table-column>
          <el-table-column prop="status_text" label="状态" width="90">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 0">{{scope.row.status_text}}</el-tag>
              <el-tag v-else-if="scope.row.status === 1" type="success">{{scope.row.status_text}}</el-tag>
              <el-tag v-else type="danger">{{scope.row.status_text}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" width="120">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <!-- 操作 -->
            <template slot-scope="scope">
              <!-- <el-button size="mini" type="warning" icon="el-icon-view" circle></el-button> -->
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="editCoupon(scope.row)" circle></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteCoupon(scope.$index,scope.row.id)"
                circle></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- table表格数据 end -->
      <!-- 分页  start-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryParam.currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="totalResult">
      </el-pagination>
      <!-- 分页  end> -->
    </el-card>
    <!-- 表单 start -->
    <el-dialog title="创建/编辑优惠卷" :visible.sync="couponFormVisible" @close="closeOptionForm" width="35%" center>
      <el-form :model="couponForm" :rules="couponFormRules" ref="couponFormRef" label-width="120px" class="demo-ruleForm">
        <el-form-item label="优惠卷名称" required prop="title">
          <el-input v-model="couponForm.title" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="抵扣金额" required prop="money">
          <el-input type="number" v-model.number="couponForm.money" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item label="发放数量" required prop="total_quantity">
          <el-input type="number" v-model.number="couponForm.total_quantity" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item label="发放开始时间" prop="start_time">
          <template>
            <el-date-picker value-format="yyyy-MM-dd HH:mm" v-model="couponForm.start_time" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </template>
        </el-form-item>
        <el-form-item label="发放结束时间" prop="end_time">
          <template>
            <el-date-picker value-format="yyyy-MM-dd HH:mm" v-model="couponForm.end_time" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </template>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="couponForm.notes"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetOptionForm">重置</el-button>
        <el-button type="primary" @click="updateOrCreateOptionForm">确认</el-button>
      </span>
    </el-dialog>
    <!-- 表单 end -->
  </div>
</template>

<script>
  export default {
    data() {
      var validateStartTime = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择发放开始时间'))
        } else {
          if (this.couponForm.end_time !== '') {
            this.$refs.couponFormRef.validateField('end_time')
          }
          callback()
        }
      }
      var validateEndTime = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择发放结束时间'))
        } else if (value <= this.couponForm.start_time) {
          callback(new Error('发放结束时间不能小于开始时间'))
        } else {
          callback()
        }
      }
      return {
        couponsDataList: [],
        totalResult: 0,
        queryStatusDict: [{
          label: '未开始',
          value: 0
        }, {
          label: '发放中',
          value: 1
        }, {
          label: '已结束',
          value: 2
        }],
        queryParam: {
          title: '',
          currentPage: 1,
          pageSize: 10
        },
        couponFormVisible: false,
        operate: 'add',
        couponForm: {},
        couponFormTem: {
          title: '',
          money: null,
          total_quantity: null,
          start_time: '',
          end_time: '',
          notes: ''
        },
        couponFormRules: {
          start_time: [{
            validator: validateStartTime,
            trigger: 'blur'
          }],
          end_time: [{
            validator: validateEndTime,
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getCouponsList()
      this.couponForm = JSON.parse(JSON.stringify(this.couponFormTem))
    },
    methods: {
      // 获取列表数据
      async getCouponsList() {
        // 获取分类列表
        const {
          data: res
        } = await this.$http.get('coupons/', {
          params: this.queryParam
        })
        // console.log(res)
        this.couponsDataList = res.data.dataList
        this.totalResult = res.data.totalResult
      },
      // 分页事件
      handleSizeChange(newSize) {
        this.queryParam.pageSize = newSize
        this.queryParam.currentPage = 1
        this.getCouponsList()
      },
      handleCurrentChange(newPage) {
        this.queryParam.currentPage = newPage
        this.getCouponsList()
      },
      async deleteCoupon(index, id) {
        // 删除
        const data = await this.$http.delete('coupons/' + id + '/')
        if (data.status === 200 && data.data.status) {
          this.$message.success('删除成功！')
          this.couponsDataList.splice(index, 1)
        }
      },
      updateOrCreateOptionForm() {
        this.$refs.couponFormRef.validate(async valid => {
          if (valid) {
            const {
              data: res
            } = this.operate === 'add' ? await this.$http.post('coupons/', this.couponForm) : await this.$http
              .put(
                'coupons/' + this.couponForm.id + '/', this.couponForm)
            console.log(res)
            if (res.status) {
              var message = this.operate === 'add' ? '添加成功！' : '编辑成功！'
              this.$message.success(message)
              this.couponFormVisible = false
              this.operate = 'add'
              this.getCouponsList()
            } else {
              this.$message.error('操作失败！')
            }
          }
        })
      },
      editCoupon(coupon) {
        this.operate = 'edit'
        this.couponForm = coupon
        this.couponFormVisible = true
      },
      // 重置表单
      resetOptionForm() {
        this.couponForm = JSON.parse(JSON.stringify(this.couponFormTem))
        this.$refs.couponFormRef.resetFields()
      },
      // 关闭表单
      closeOptionForm() {
        this.resetOptionForm()
        this.couponFormVisible = false
      }
    }
  }
</script>

<style>
</style>
